#include "SeqList.h"

void SLInit(SeqLsit* ps)
{
	assert(ps);
	ps->data = (SLDatatype*)malloc(sizeof(SLDatatype) * INIT_CAPACITY);
	if (ps->data == NULL)
	{
		perror("malloc fail");
		return;
	}
	ps->size = 0;
	ps->capacity = INIT_CAPACITY;
}

void SLDestory(SeqLsit* ps)
{
	assert(ps);
	free(ps->data);
	ps->data = NULL;
	ps->capacity = ps->size = 0;
}
void SLPrint(SeqLsit* ps)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->data[i]);
	}
	printf("\n");
}
void SLCheckCapacity(SeqLsit* ps)
{
	assert(ps);
	if (ps->size == ps->capacity)
	{
		SLDatatype* tmp = (SLDatatype*)realloc(ps->data, ps->capacity * 2 * sizeof(SLDatatype));
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		ps->data = tmp;
		ps->capacity = 2 * ps->capacity;
	}
}

void SLPushBack(SeqLsit* ps, SLDatatype x)
{
	/*assert(ps);
	SLCheckCapacity(ps);
	ps->data[ps->size++] = x;*/

	SLInsert(ps, ps->size, x);
}

void SLPushFront(SeqLsit* ps, SLDatatype x)
{
	/*assert(ps);
	SLCheckCapacity(ps);
	for (int i = ps->size-1; i >=0; i--)
	{
		*((ps->data) + i + 1) = *((ps->data) + i);
	}
	ps->data[0] = x;
	ps->size++;*/
	SLInsert(ps, 0, x);

}

void SLPopBack(SeqLsit* ps)
{
	assert(ps->size > 0);
	/*if (ps->size == 0)
	{
		return;
	}*/
	ps->size--;
	//SLErase(ps, ps->size-1);

}

void SLPopFront(SeqLsit* ps)
{
	assert(ps->size > 0 && ps);
	for (int i = 0; i < ps->size - 1; i++)
	{
		ps->data[i] = ps->data[i + 1];
	}
	ps->size--;
	//SLErase(ps, 0);
}

void SLInsert(SeqLsit* ps, int pos, SLDatatype x)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);
	SLCheckCapacity(ps);
	for (int i = ps->size;i>= pos; i--)
	{
		ps->data[i] = ps->data[i - 1];
	}
	ps->data[pos] = x;
	ps->size++;

}

void SLErase(SeqLsit* ps, int pos)
{
	assert(ps);
	assert(pos >= 0 && pos <ps->size);

	for (int i = pos; i < ps->size - 1; i++)
	{
		ps->data[i] = ps->data[i + 1];
	}
	ps->size--;
	
}


int SLFind(SeqLsit* ps, SLDatatype x)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->data[i] == x)
		{
			return i; 
		}
	}
	return -1;
}
